package com.sinoglobal.ningxia.activity.vip;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.orhanobut.logger.Logger;
import com.sinoglobal.dumping.base.Dumpling_SharedPreferenceUtil;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.base.BaseActivity;
import com.sinoglobal.ningxia.beans.RegistVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.ningxia.utils.TextUtil;
import com.sinoglobal.ningxia.utils.UserUtils;
import com.sinoglobal.ningxia.utils.ValidUtil;
import com.sinoglobal.ningxia.widget.PwdSlipButton;
import com.sinoglobal.ningxia.widget.PwdSlipButton.OnChangedListener;

import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lms
 * @title: SetRegistInfoActivity.java
 * @package com.sinoglobal.ningxia.activity.vip
 * @description: 设置注册信息页面
 * @date 2014-6-23 下午4:44:01
 */
public class RegistInfoSet extends BaseActivity implements OnFocusChangeListener {
    protected static final int TEXT_MAX = 12;
    private TextView complete;// 完成
    private EditText nickname;// 昵称
    private EditText password;// 密码
    private String usernameStr;// 手机号字符串
    private String nicknameStr;// 昵称字符串
    private String passwordStr;// 密码字符串
    private TextView limitNickname;// 昵称输入异常的提示
    private TextView limitPwd;// 密码输入 异常的提示
    private PwdSlipButton slipButton;// 改变密码文本样式
    private String validNickname;// 验证昵称的结果字符串
    private String validPassword;// 验证密码的结果字符串

    private CharSequence temp;
    private int selectionStart;
    private int selectionEnd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vip_set_regist_info);
        openChenJInShi();//开启沉浸式
        init();
        setListener();
    }

    // 初始化
    private void init() {
        titleView.setText(R.string.set_nickname_pwd);
        nickname = (EditText) findViewById(R.id.edit_regist_nickname);
        password = (EditText) findViewById(R.id.edit_regist_pwd);
        complete = (TextView) findViewById(R.id.regist_finish_tv);
        limitNickname = (TextView) findViewById(R.id.limit_regist_nickname);
        limitPwd = (TextView) findViewById(R.id.limit_regist_pwd);
        usernameStr = getIntent().getStringExtra("username");
        slipButton = (PwdSlipButton) findViewById(R.id.slipButton1);
    }

    // 添加控件的事件监听
    private void setListener() {
        nickname.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                temp = s;
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                int count = 0;
                selectionStart = nickname.getSelectionStart();
                selectionEnd = nickname.getSelectionEnd();
                Pattern p = Pattern.compile("[\u4E00-\u9FA5]+");
                for (int i = 0; i < temp.length(); i++) {
                    String ss = temp.toString().substring(i, i + 1);
                    Matcher matcher = p.matcher(ss);
                    if (matcher.matches()) {
                        count = count + 1;
                    }
                }

                if (temp.toString().getBytes().length - count > TEXT_MAX) {
                    s.delete(selectionStart - 1, selectionEnd);
                    nickname.setText(s);
                    Toast.makeText(FlyApplication.context, "昵称仅支持1-12个字符，限中文、字母", Toast.LENGTH_SHORT).show();
                }

            }
        });
        complete.setOnFocusChangeListener(this);
        password.setOnFocusChangeListener(this);
        //密码样式
        slipButton.SetOnChangedListener(new OnChangedListener() {

            @Override
            public void OnChanged(boolean CheckState) {
                ItktLog.i("----------->" + CheckState);
                passwordStr = password.getText().toString().trim();
                if (CheckState) {
                    password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    password.setSelection(passwordStr.length());
                } else {
                    password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
                    password.setSelection(passwordStr.length());
                }
            }
        });

        //完成
        complete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 得到输入的昵称和密码字符串
                nicknameStr = nickname.getText().toString().trim();
                passwordStr = password.getText().toString().trim();
                try {
                    validNickname = ValidUtil.validNickName(nicknameStr);
                    validPassword = ValidUtil.validPassword(passwordStr);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                // 对输入的昵称和密码进行验证
                if (!TextUtil.stringIsNull(validNickname)) {// 校验信息不为空时，输入的昵称不符合规则
                    limitNickname.setText(validNickname);
                    return;
                }
                if (!TextUtil.stringIsNull(validPassword)) {// 校验信息不为空时，输入的昵称不符合规则
                    limitPwd.setText(validPassword);
                    return;
                }
                limitNickname.setText(MContants.EMPTY_STRING);
                limitPwd.setText(MContants.EMPTY_STRING);
                validNickname(nicknameStr);
                validPwd(passwordStr);
                String message = "正在注册...";// dialog的提示内容
                new ItktAsyncTaskWithDialog<Void, Void, RegistVo>(message, true, false) {

                    @Override
                    public RegistVo before(Void... params) throws Exception {
                        return RemoteImpl.getInstance().regist(usernameStr, nicknameStr, passwordStr);
                    }

                    @Override
                    public void after(RegistVo result) {
                        if (null == result) { // 数据为空，重新注册
                            showShortToastMessage(getResources().getString(R.string.registe_fail));
                            return;
                        }
                        if (Code.CODE_SUCCESS != result.getCode()) {
                            showShortToastMessage(result.getMessage());
                            return;
                        }
                        //保存前先清空之前存储的东西
                        clearSharePerfrerence();

                        FlyApplication.userId = result.getId();
                        SharedPreferenceUtil.saveString(FlyApplication.context, "id", result.getId());
                        SharedPreferenceUtil.saveString(FlyApplication.context, "username", result.getUsername());
                        SharedPreferenceUtil.saveString(FlyApplication.context, "nickname", result.getNickname());
                        SharedPreferenceUtil.saveString(FlyApplication.context, "score", result.getScore());

                        Intent intent = new Intent(RegistInfoSet.this, PersonalInfoSet.class);
                        startActivity(intent);
                        finish();
                        popAllActivityExceptOne(getClass());
                    }

                    @Override
                    public void exception() {

                    }
                }.execute();
            }
        });
    }

    private void clearSharePerfrerence() {
        SharedPreferenceUtil.saveString(FlyApplication.context, "autoName", "");//用户名
        SharedPreferenceUtil.saveString(FlyApplication.context, "autoPwd", "");//密码
        Logger.i("清空SP");
        UserUtils.ExitSccess();
        Dumpling_SharedPreferenceUtil.clear(mActivity);
    }

    // 验证输入的密码
    protected void validPwd(String pwd) {
        String validPassword = ValidUtil.validPassword(pwd);// 校验密码的结果字符串
        if (!TextUtil.stringIsNull(validPassword)) {// 校验信息不为空时，输入的密码不符合规则
            limitPwd.setText(validPassword);
            return;
        }
        limitPwd.setText(MContants.EMPTY_STRING);
    }

    // 验证输入的规则
    protected void validNickname(String nickname) {
        try {
            // 校验密码的结果字符串
            validNickname = ValidUtil.validNickName(nickname);
            // 校验信息不为空时，输入的昵称不符合规则
            if (!TextUtil.stringIsNull(validNickname)) {
                limitNickname.setText(validNickname);
                return;
            }
            limitNickname.setText(MContants.EMPTY_STRING);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        finish();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.regist_finish_tv:
                nicknameStr = nickname.getText().toString().trim();
                validNickname(nicknameStr);
                passwordStr = password.getText().toString().trim();
                validPwd(passwordStr);
                break;
            case R.id.edit_regist_pwd:
                nicknameStr = nickname.getText().toString().trim();
                validNickname(nicknameStr);
                break;
        }
    }
}
